import express from "express";
import { ObjectId } from "mongodb";
import authMiddleware from "../middleware/auth.js";
import { getDb } from "../config/database.js";

const router = express.Router();
const COLLECTION = "waybill_recharge";

// 获取充值记录列表
router.get("/", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const {
      page = 1,
      limit = 10,
      search = "",
      platform = "",
      expressCompany = "",
      paymentStatus = "",
    } = req.query;
    const skip = (Number(page) - 1) * Number(limit);

    // 构建查询条件
    const query = {};

    if (search) {
      query.$or = [
        { shopName: { $regex: search, $options: "i" } },
        { customerName: { $regex: search, $options: "i" } },
        {
          transactionNumbers: { $elemMatch: { $regex: search, $options: "i" } },
        },
      ];
    }

    if (platform) {
      query.platform = platform;
    }

    if (expressCompany) {
      query.expressCompany = expressCompany;
    }

    // 聚合查询，关联客户和店铺信息
    const pipeline = [
      { $match: query },
      {
        $lookup: {
          from: "customers",
          localField: "customerId",
          foreignField: "_id",
          as: "customer",
        },
      },
      {
        $lookup: {
          from: "shops",
          localField: "shopId",
          foreignField: "_id",
          as: "shop",
        },
      },
      {
        $addFields: {
          customerName: { $arrayElemAt: ["$customer.name", 0] },
          shopName: { $arrayElemAt: ["$shop.shopName", 0] },
          platform: { $arrayElemAt: ["$shop.platform", 0] },
        },
      },
      { $project: { customer: 0, shop: 0 } },
    ];

    // 如果有支付状态筛选，添加筛选条件
    if (paymentStatus) {
      pipeline.push({
        $addFields: {
          paymentStatus: {
            $cond: {
              if: { $eq: ["$actualAmount", 0] },
              then: "unpaid",
              else: {
                $cond: {
                  if: { $gte: ["$actualAmount", "$totalAmount"] },
                  then: "paid",
                  else: "partial",
                },
              },
            },
          },
        },
      });
      pipeline.push({ $match: { paymentStatus } });
    }

    pipeline.push({ $sort: { createdAt: -1 } });
    pipeline.push({ $skip: skip });
    pipeline.push({ $limit: Number(limit) });

    const records = await db
      .collection(COLLECTION)
      .aggregate(pipeline)
      .toArray();

    // 获取总数
    const countPipeline = [...pipeline.slice(0, -2)];
    countPipeline.push({ $count: "total" });
    const countResult = await db
      .collection(COLLECTION)
      .aggregate(countPipeline)
      .toArray();
    const total = countResult.length > 0 ? countResult[0].total : 0;

    res.json({
      records,
      total,
      page: Number(page),
      limit: Number(limit),
      totalPages: Math.ceil(total / Number(limit)),
    });
  } catch (error) {
    console.error("获取充值记录失败:", error);
    res.status(500).json({ error: "获取充值记录失败" });
  }
});

// 获取未付的面单充值记录
router.get("/unpaid-records", authMiddleware, async (req, res) => {
  try {
    const db = getDb();

    const pipeline = [
      {
        $addFields: {
          paymentStatus: {
            $cond: {
              if: { $gte: ["$actualAmount", "$totalAmount"] },
              then: "paid",
              else: "unpaid",
            },
          },
        },
      },
      { $match: { paymentStatus: "unpaid" } },
      {
        $lookup: {
          from: "shops",
          localField: "shopId",
          foreignField: "_id",
          as: "shop",
        },
      },
      {
        $addFields: {
          shopName: { $arrayElemAt: ["$shop.shopName", 0] },
          platform: { $arrayElemAt: ["$shop.platform", 0] },
        },
      },
      { $project: { shop: 0 } },
      { $sort: { createdAt: -1 } },
    ];

    const records = await db
      .collection(COLLECTION)
      .aggregate(pipeline)
      .toArray();

    res.json({ records });
  } catch (error) {
    console.error("获取未付充值记录失败:", error);
    res.status(500).json({ error: "获取未付充值记录失败" });
  }
});

// 创建充值记录
router.post("/", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const {
      customerId,
      shopId,
      expressCompany,
      quantity,
      actualAmount,
      paymentMethod,
      transactionTime,
      confirmTime,
      transactionNumbers,
    } = req.body;

    // 验证必填字段
    if (
      !customerId ||
      !shopId ||
      !expressCompany ||
      !quantity ||
      actualAmount === undefined ||
      !paymentMethod
    ) {
      return res.status(400).json({ error: "所有必填字段都不能为空" });
    }

    // 验证客户和店铺是否存在
    const customer = await db
      .collection("customers")
      .findOne({ _id: new ObjectId(customerId) });
    if (!customer) {
      return res.status(400).json({ error: "所选客户不存在" });
    }

    const shop = await db
      .collection("shops")
      .findOne({ _id: new ObjectId(shopId) });
    if (!shop) {
      return res.status(400).json({ error: "所选店铺不存在" });
    }

    // 验证店铺是否属于该客户
    if (shop.customerId.toString() !== customerId) {
      return res.status(400).json({ error: "所选店铺不属于该客户" });
    }

    // 验证快递公司是否在店铺的快递公司列表中
    if (!shop.expressCompanies.includes(expressCompany)) {
      return res
        .status(400)
        .json({ error: "所选快递公司不在该店铺的快递公司列表中" });
    }

    // 计算金额
    const prepaidAmount = customer.prepaidAmount || 0;
    const totalAmount = quantity * prepaidAmount;

    // 创建新充值记录
    const newRecord = {
      customerId: new ObjectId(customerId),
      customerName: customer.name,
      shopId: new ObjectId(shopId),
      shopName: shop.shopName,
      platform: shop.platform,
      expressCompany,
      quantity: Number(quantity),
      prepaidAmount,
      totalAmount,
      actualAmount: Number(actualAmount) || 0,
      paymentMethod,
      transactionTime: transactionTime ? new Date(transactionTime) : null,
      confirmTime: confirmTime ? new Date(confirmTime) : null,
      transactionNumbers: transactionNumbers || [],
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    const result = await db.collection(COLLECTION).insertOne(newRecord);
    newRecord._id = result.insertedId;

    res.status(201).json(newRecord);
  } catch (error) {
    console.error("创建充值记录失败:", error);
    res.status(500).json({ error: "创建充值记录失败" });
  }
});

// 更新充值记录
router.put("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { id } = req.params;
    const {
      customerId,
      shopId,
      expressCompany,
      quantity,
      actualAmount,
      paymentMethod,
      transactionTime,
      confirmTime,
      transactionNumbers,
    } = req.body;

    // 验证必填字段
    if (
      !customerId ||
      !shopId ||
      !expressCompany ||
      !quantity ||
      actualAmount === undefined ||
      !paymentMethod
    ) {
      return res.status(400).json({ error: "所有必填字段都不能为空" });
    }

    // 验证客户和店铺是否存在
    const customer = await db
      .collection("customers")
      .findOne({ _id: new ObjectId(customerId) });
    if (!customer) {
      return res.status(400).json({ error: "所选客户不存在" });
    }

    const shop = await db
      .collection("shops")
      .findOne({ _id: new ObjectId(shopId) });
    if (!shop) {
      return res.status(400).json({ error: "所选店铺不存在" });
    }

    // 验证店铺是否属于该客户
    if (shop.customerId.toString() !== customerId) {
      return res.status(400).json({ error: "所选店铺不属于该客户" });
    }

    // 验证快递公司是否在店铺的快递公司列表中
    if (!shop.expressCompanies.includes(expressCompany)) {
      return res
        .status(400)
        .json({ error: "所选快递公司不在该店铺的快递公司列表中" });
    }

    // 计算金额（面单预充金额和应收金额不可更改）
    const prepaidAmount = customer.prepaidAmount || 0;
    const totalAmount = quantity * prepaidAmount;

    // 更新充值记录
    const updateData = {
      $set: {
        customerId: new ObjectId(customerId),
        customerName: customer.name,
        shopId: new ObjectId(shopId),
        shopName: shop.shopName,
        platform: shop.platform,
        expressCompany,
        quantity: Number(quantity),
        prepaidAmount,
        totalAmount,
        actualAmount: Number(actualAmount) || 0,
        paymentMethod,
        transactionTime: transactionTime ? new Date(transactionTime) : null,
        confirmTime: confirmTime ? new Date(confirmTime) : null,
        transactionNumbers: transactionNumbers || [],
        updatedAt: new Date(),
      },
    };

    const result = await db
      .collection(COLLECTION)
      .findOneAndUpdate({ _id: new ObjectId(id) }, updateData, {
        returnDocument: "after",
      });

    if (!result) {
      return res.status(404).json({ error: "充值记录不存在" });
    }

    res.json(result);
  } catch (error) {
    console.error("更新充值记录失败:", error);
    res.status(500).json({ error: "更新充值记录失败" });
  }
});

// 获取单个充值记录
router.get("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const pipeline = [
      { $match: { _id: new ObjectId(req.params.id) } },
      {
        $lookup: {
          from: "customers",
          localField: "customerId",
          foreignField: "_id",
          as: "customer",
        },
      },
      {
        $lookup: {
          from: "shops",
          localField: "shopId",
          foreignField: "_id",
          as: "shop",
        },
      },
      {
        $addFields: {
          customerName: { $arrayElemAt: ["$customer.name", 0] },
          shopName: { $arrayElemAt: ["$shop.shopName", 0] },
          platform: { $arrayElemAt: ["$shop.platform", 0] },
        },
      },
      { $project: { customer: 0, shop: 0 } },
    ];

    const records = await db
      .collection(COLLECTION)
      .aggregate(pipeline)
      .toArray();
    const record = records[0];

    if (!record) {
      return res.status(404).json({ error: "充值记录不存在" });
    }

    res.json(record);
  } catch (error) {
    console.error("获取充值记录失败:", error);
    res.status(500).json({ error: "获取充值记录失败" });
  }
});

// 删除充值记录
router.delete("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const result = await db
      .collection(COLLECTION)
      .findOneAndDelete({ _id: new ObjectId(req.params.id) });

    if (!result) {
      return res.status(404).json({ error: "充值记录不存在" });
    }

    res.json({ message: "充值记录删除成功" });
  } catch (error) {
    console.error("删除充值记录失败:", error);
    res.status(500).json({ error: "删除充值记录失败" });
  }
});

// 根据客户ID获取充值记录统计
router.get("/stats/customer/:customerId", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { customerId } = req.params;

    const pipeline = [
      { $match: { customerId: new ObjectId(customerId) } },
      {
        $group: {
          _id: null,
          totalRecords: { $sum: 1 },
          totalQuantity: { $sum: "$quantity" },
          totalAmount: { $sum: "$totalAmount" },
          totalActualAmount: { $sum: "$actualAmount" },
        },
      },
    ];

    const stats = await db.collection(COLLECTION).aggregate(pipeline).toArray();
    const result = stats[0] || {
      totalRecords: 0,
      totalQuantity: 0,
      totalAmount: 0,
      totalActualAmount: 0,
    };

    res.json(result);
  } catch (error) {
    console.error("获取客户充值统计失败:", error);
    res.status(500).json({ error: "获取客户充值统计失败" });
  }
});

export default router;
